(function (G) {
  var pick = new G.Picker();
  window["components_List_Table_Table"]({
  "component": true,
  "usingComponents": {
    "mixinput":"/components/Input/Mixinput/Mixinput"
  }
},{
template:'#TEMPLATE_components_List_Table_Table',

    props: {
    },
    data:function(){
      return {
        oid:'',
        searchValues:{
          pageSize:10,
          pageNum:1
        },
        searchValuesShow:[{}],
        models:{},
        searchs:[],
        rows:[],
        total:0,
        allChecked:false,
        pagination:[],
        actions:[],
        getUrl:'',
        canDelete:'',
        idKey:'',
        deleteKey:'id',
        canCheck:true,
        canBack:false,
        exportUrl:'',
        canAdd:false,
        textstitle:'',
        textstitleStyle:'',
        statistics:'',
        statisticsString:'',
        rowspan:'',//合并单元格关键字
        rowspans:{},
        textssearchBtn:'搜索',
        textsaddBtn:'新增',
        textseditBtn:'编辑',
        textsbackBtn:'返回',
        textsexportBtn:'导出',
        textsoutEditBtn:'退出编辑',
        textsdeletsBtn:'批量删除',
        textsallCheckBtn:'全选',
        textsunAllCheckBtn:'反选',
        textscheckBtn:'选择',
        btns:[]
      }
    },
    methods:{
      showTip:function(tip){
        G.alertx(tip);
      },
      exportExcel:function(event){
        //通用导出
        var exportUrl = this.getData('exportUrl'),searchValues = this.getData('searchValues');
        if(exportUrl) {
          if(exportUrl == 'action'){
            var actions = G.Storage.get(this.oid);
            if (actions.export && typeof actions.export.action == 'function') actions.export.action.call(this,{type:'export',event:event,detail:searchValues})
          }else if(!searchValues.createTime){
            pick.pick({
                items:[
                  {name:'前一周',value:7},
                  {name:'前一月',value:31},
                  {name:'前一季度',value:93},
                  {name:'前半年',value:180},
                  {name:'前一年',value:365},
                  {name:'全部',value:365 * 1000}
                ],//选项数据
                title:'选择时间范围',
                pickBox:`right:32px;left:auto;top:${event.pageY}px`,
                index:1//默认选中
            },res => {
              if(res.data && res.data.value){
                searchValues.createTime = JSON.stringify({
                  $gte: new Date().getTime() - res.data.value * 24 * 60 * 60 * 1000
                })
                goDown()
              }
            })
          }else{
            goDown()
          }
        }
        function goDown(){
            exportUrl = exportUrl.replace(new RegExp('^{(.+)}', 'g'), function($0, $1) {
                return G.Storage.get($1) || ('{' + $1 + '}');
            })
            if (exportUrl.indexOf('http') != 0) exportUrl = G.Storage.get('APIURL') + exportUrl;
            var headers = G.Storage.get('ajaxHeader'),_exportUrl = [];
            for(var i = 0; i < headers.length; i ++) _exportUrl.push(headers[i].key + '=' + headers[i].value);
            for(var key in searchValues) if(key != 'pageSize' && key != 'pageNum') _exportUrl.push(key + '=' + searchValues[key]);          
            G.showFile(exportUrl + (exportUrl.indexOf('?') > -1 ? '&' : '?') + _exportUrl.join('&'),false,'excel');
        }
      },
      computPagination:function(){
        var pageTotal = Math.ceil(this.total / this.searchValues.pageSize);
        var pagination = [{name:'<',value:'prev',unClick:this.searchValues.pageNum == 1}];
        var prev = false,next = false;
        for(var i = 0; i < pageTotal; i ++){
          if(i == 0 || i == pageTotal - 1){
            pagination.push({name:i + 1,value:i + 1,isActive:this.searchValues.pageNum == i + 1});
          }else if(i + 1 - this.searchValues.pageNum < -2){
            if(!prev){
              prev = true;
              pagination.push({name:'...',value:'prevmore'});
            }
          }else if(i + 1 - this.searchValues.pageNum > 2){
            if(!next){
              next = true;
              pagination.push({name:'...',value:'nextmore'});
            }
          }else{
            pagination.push({name:i + 1,value:i + 1,isActive:this.searchValues.pageNum == i + 1});
          }
        }
        pagination.push({name:'>',value:'next',unClick:this.searchValues.pageNum == pageTotal});
        this.setData({pagination:pagination.length > 3 ? pagination : []});
      },
      pageChange:function(paginate){
        if(paginate.unClick || paginate.isActive) return false;
        switch(paginate.value){
          case 'prev':
            this.searchValues.pageNum --;
            break;
          case 'next':
            this.searchValues.pageNum ++;
            break;
          case 'prevmore':
            this.searchValues.pageNum -= 3;
            break;
          case 'nextmore':
            this.searchValues.pageNum += 3;
            break;
          default:
            this.searchValues.pageNum = paginate.value;
            break;
        }
        this.load();
      },
      change:function(event){
        var value = event.detail.value;
        if(!value && value !== 0 && value !== '0' && value !== '0') value = undefined;
        this.searchValues[event.detail.id] = value;
        this.searchValuesShow.splice(0,1);
        this.searchValuesShow.push(this.searchValues);
      },
      filter:function(item,key){
        var edit = G.Storage.get(this.oid + 'edit');
        var rc = '',model = this.models[key];
        if(model){
          if(typeof model.model == 'function'){
            model = model.model.call(this,item,model) || model;
          }else if(typeof model.model == 'object' && model.model){
            model = model.model;
          }
        }
        if(!model) return ['',''];
        switch (model.type) {
          case 'radio':
          case 'select':
            for(var i = 0; i < model.attr.actions.length; i ++){
              if(item[key] == model.attr.actions[i].value) {
                rc = model.attr.actions[i].name;
                break;
              }
            }
            break;
          case 'checkbox':
            rc = [];
            for(var i = 0; i < model.attr.actions.length; i ++){
              if(new RegExp(',' + model.attr.actions[i].value + ',').test(',' + item[key] + ',')) rc.push(this.models[key].attr.actions[i].name);
            }
            rc = rc.join(',');
            break;
          case 'datetime':
            rc = !item[key] ? '' : G.date(-(-item[key])).toLocalString();
            break;
          case 'switch':
            if(edit[key]){
              rc = item[key] == 1 ? true : false;
            }else{
              rc = item[key] == 1 ? '是' : '否';
            }
            break;
          case 'image':
            rc = typeof item[key] == 'string' ? item[key].split(',')[0] : '';
            rc = rc.charAt(0) === '/' ? G.Storage.get('APIURL') + rc : rc;
            return rc;
          case 'file':
            rc = G.string(item[key]).parse([])[0];
            rc = rc && rc.originalname ? rc.originalname : '';
            break;
          case 'onlyselect':
            var keyName = key.replace(/(Id$)|(_id$)/,'') + model.attr.skey.replace(/([A-Za-z])/,function($0,$1){
              return $1.toUpperCase();
            });
            rc = item[keyName] || item[key];
            break;
          default:
            rc = item[key];
            if(/input|textarea/.test(model.type) || !model.type){
              let stringmax = model.attr && model.attr.stringmax ? model.attr.stringmax : 16
              rc = [typeof rc == 'string' && rc.length > stringmax ? rc.substring(0,stringmax) + '...' : rc,rc];
            }
            break;
        }
        return rc
      },
      check:function(index){
        if(index > -1){
          this.rows[index].checked = !this.rows[index].checked;
        }else{
          this.allChecked = !this.allChecked;
          for(var i = 0; i < this.rows.length; i ++){
            this.rows[i].checked = this.allChecked;
          }
        }
      },
      selected:function(){
        var rc = [];
        for(var i = 0; i < this.rows.length; i ++){
          if(this.rows[i].checked) rc.push(this.rows[i]);
        }
        return rc;
      },
      doAction:function(action,index,event){
        var actions = G.Storage.get(this.oid);
        if (actions[action]){
          switch (action) {
            case 'delet':
              this.delet.call(this,index);
              break;
            default:
              if (actions[action] && typeof actions[action].action == 'function') {
                actions[action].action.call(this,{ type: action,event:event, detail: G.clone(this.rows[index]) })
              }
              break
          }
        }
      },
      add:function(event){
        var actions = G.Storage.get(this.oid);
        if (actions.add && typeof actions.add.action == 'function') actions.add.action.call(this,{type:'add',event:event,detail:{}})
      },
      editList:function(event,model,row){
        var edit = G.Storage.get(this.oid + 'edit');
        var _this = this,data = {id:row.id};
        data[model.id] = event.detail.value;
        if(model.type == 'switch') data[model.id] = data[model.id] ? 1 : 0;
        if(typeof edit[model.id] == 'string'){
          G.ajax(edit[model.id],function(ret){
            _this.load();
            G.alertx('修改 ' + model.label + (ret.errorMsg ? ' 失败,' + ret.errorMsg : ' 成功!'));
          },{
            data:data,
            meth:'PUT'
          })
        }else if(typeof edit[model.id] == 'function'){
          edit[model.id].call(this,data);
        }
      },
      delet:function(index){
        var actions = G.Storage.get(this.oid);
        var ids = [],_this = this;
        if(index > -1){
          ids.push(this.rows[index][this.deleteKey]);
        }else{
          for(var i = 0; i < this.rows.length; i ++){
            if(this.rows[i].checked) ids.push(this.rows[i][this.deleteKey]);
          }
        }
        if(ids.length){
          G.confirmx('确定要对此' + ids.length + '项进行删除?',function(){
            var data = {};
            data[_this.deleteKey] = {$in:ids};
            if (typeof actions.delet.action == 'string'){
              G.ajax(actions.delet.action, function (ret) {
                G.alertx(ret.errorMsg || '删除成功!!');
                if (!ret.errorMsg) _this.refresh();
              }, {
                  meth: 'DELETE',
                  data: data
                })
            } else if (typeof actions.delet.action == 'function'){
              actions.delet.action.call(_this,{ type: 'delete', detail: data})
            }
          })
        }else{
          G.alertx('请选择需要删除的项')
        }
      },
      val:function(s){
        if(s == undefined){
          return this.selected();
        }else{
          for(var i = 0; i < this.rows.length; i ++){
            if(s[this.rows[i][this.idKey]]) {
              this.rows[i].checked = true;
            }
          }
        }
      },
      getRows:function(){
        return this.rows;
      },
      refresh:function(next){
        this.searchValues.pageNum = 1;
        this.load(next);
      },
      load: function (next){
        var getUrl = this.getData('getUrl'), url = getUrl, data = {}, meth = 'GET',dataJson = true,urlQuery = false,rowspan = this.getData('rowspan');
        if (typeof getUrl == 'object') {
          if (getUrl.data) data = getUrl.data;
          if (getUrl.url) url = getUrl.url;
          if (getUrl.meth) meth = getUrl.meth;
          if (getUrl.dataJson === false) dataJson = false;
          if (getUrl.urlQuery) urlQuery = true;
        }
        var models = this.getData('models');
        for(var i = 0; i < this.searchs.length; i ++) models[this.searchs[i].id] = this.searchs[i];
        for(var key in this.searchValues){
          data[key] = this.searchValues[key];
          if(models[key] && models[key].type == 'onlyselect'){
            var value = G.string(this.searchValues[key]).parse({}),vkey = models[key].attr.vkey || 'id';
            data[key] = value[vkey] ? (key == 'unitId' ? { $regex: value[vkey] } : value[vkey]) : undefined;
          } else if(models[key] && models[key].type == 'datetime' && data[key] != undefined){
            if(/END$/.test(key)){
              continue;
            }else{
              if(this.searchValues[key + 'END']){
                data[key] = {$gte:this.searchValues[key],$lte:this.searchValues[key + 'END']};
              }else{
                data[key] = {$gte:this.searchValues[key]};
              }
            }
          }else if(models[key] && !/select|date|time/.test(models[key].type) && data[key] != undefined && !models[key].unRegex){
            data[key] = {$regex:this.searchValues[key]};
          }
          if (data[key] === '') {
            data[key] = undefined;
          }
        }
        function formatRow(rows){
          if(rowspan){
            var rowSpanStart = '';
            for(var i = 0; i < rows.length; i ++) {
              if(typeof actions.addDataChange == 'function') actions.addDataChange.call(rows[i],rows[i],i);
              if(rowSpanStart && rowSpanStart[rowspan] == rows[i][rowspan]){
                rowSpanStart.rowspan ++;
                rows[i].rowspan = '';
              }else{
                rows[i].rowspan = 1;
                rowSpanStart = rows[i];
              }
            }
          }else if(typeof actions.addDataChange == 'function'){
            for(var i = 0; i < rows.length; i ++) actions.addDataChange.call(rows[i],rows[i],i);
          }
        }
        var _this = this,actions = G.Storage.get(this.oid);
        if(url instanceof Array){
          (new G.SQLite(url)).find(data,function(ret){
            formatRow(ret.rows);
            _this.setData({
              rows:ret.rows,
              total:ret.total,
              allChecked:false,
              statisticsString:G.string(_this.getData('statistics'))._eval(ret)
            });
          },{pageNum:this.searchValues.pageNum,pageSize:this.searchValues.pageSize})
        }else{
          G.ajax(url,function(ret){
            if(!ret.errorMsg){
              formatRow(ret.rows);
              _this.setData({
                rows:ret.rows,
                total:ret.total,
                allChecked:false,
                statisticsString:G.string(_this.getData('statistics'))._eval(ret)
              });
            }else{
              _this.setData({rows:[],allChecked:false,pageTotal:1,statisticsString:''})
            }
            _this.computPagination();
            if(typeof next == 'function') next.call({res:ret});
          },{data:data,meth:meth,loading:false,dataJson:dataJson,urlQuery:urlQuery})
        }
      },
      init:function(options){
        var _actions = [],hasEdit = true,hasDelete = true;
        options.actions = options.actions || {};
        options.oid = options.oid || G.zIndex();
        var actions = {},edit = {};
        edit = options.edit || {};
        for(var key in options.actions){
          actions[key] = options.actions[key];
          if(!actions[key]) continue
          if (key == 'add' && actions[key]) {
            options.canAdd = true;
            continue;
          } else if (key == 'export') {
            options.exportUrl = 'action';
            options.textsexportBtn = actions[key].name;
            continue;
          } else if (key == 'delet') {
            if(!actions[key]) continue;
            options.canDelete = true;
            //options.canCheck = true;
            options.actions[key].className = 'danger ' + (options.actions[key].className || '')
          }else if(key == 'edit'){
            if(!actions[key]) continue;
            options.actions[key].className = 'primary ' + (options.actions[key].className || '')
          }
          _actions.push({
            action: key,
            name: options.actions[key].name,
            style:options.actions[key].style || '',
            className: 'button mini ' + (options.actions[key].className || '')
          });
        }
        actions.addDataChange = options.addDataChange;
        G.Storage.set(options.oid,actions);
        G.Storage.set(options.oid + 'edit',edit);
        options.actions = _actions;
        if(options.searchKey){
          var searchKey = options.searchKey ? options.searchKey.split(',') : [];
          var searchs = options.searchs || [],searchValues = G.clone(this.searchValues);
          for(var i = 0; i < searchKey.length; i ++){
            var model = {};
            if(searchKey[i] == 'unitId'){
              model = {
                id:'unitId',
                label:'所属' + (G.Storage.get('nickNames').unit || '单位'),
                attr:{
                  skey: 'name',
                  vkey: 'unitId',
                  url: '/api/model/unit',
                  canClear:true,
                  title: '请选择' + (G.Storage.get('nickNames').unit || '单位')
                },
                type:'onlyselect'
              }
            }else if(options.models[searchKey[i]]){
              model = G.clone(options.models[searchKey[i]]);
            }
            if (model && model.type != 'checkbox') {
              if (model.type == 'radio') model.type = 'select';
              if (model.type == 'switch') {
                model.type = 'select';
                model.attr = model.attr || {};
                model.attr.actions = [{ name: '否', value: 0 }, { name: '是', value: 1 }]
              }
              if (model.type == 'textarea') model.type = 'input';
              model.attr = model.attr || {};
              model.attr.placeholder = model.label;
              searchValues[searchKey[i]] = model.defaultValue;
              if (model.type == 'select') {
                model.attr.actions.unshift({
                  name: '全部',
                  value: ''
                })
              }
              model.id = model.id || searchKey[i];
              model.type = model.type || 'input';
              searchs.push(model);
            }
          }
          options.searchs = searchs;
          options.searchValues = searchValues;
          options.searchValuesShow = [searchValues];
        }
        this.setData(options);
      }
    }
  })
})(Y)
